<?php
/**
 * ClassName: CardLogService
 * Description: 卡充值+所有消费记录
 * @Author 周昌
 * @Create 2023/12/25 16:47
 */

namespace service\admin;


use libs\Tool;
use model\CardCateModel;
use model\HospitalModel;
use model\MemberInfoModel;
use model\MemberModel;
use service\BaseService;
use think\Db;

class CardLogService extends BaseService
{
    protected static $model='model\CardLogModel';
    public static $card_log_type=['充值','开药消费','治疗服务消费'];
    public static $card_log_type_index=['recharge'=>0,'take_medicine'=>1,'treatment'=>2];
    public static $log_pay_type=['卡支付','线下支付','微信支付'];//支付方式
    public static $log_pay_type_index=['card_pay'=>0,'offline_pay'=>1,'wechat_pay'=>2];

    //记录类型下拉选择
    public static function cardLogTypeSelect()
    {
        static $card_log_type;
        if(empty($card_log_type)){
            foreach (self::$card_log_type as $k=>$v){
                $row=[];
                $row['id']=$k;
                $row['name']=$v;
                $card_log_type[]=$row;
            }
            array_unshift($card_log_type,['id'=>'','name'=>'-----请选择-----']);
        }
        return $card_log_type;
    }
    //支付列席下了选择
    public static function payTypeSelect()
    {
        static $log_pay_type;
        if(empty($log_pay_type)){
            foreach (self::$log_pay_type as $k=>$v){
                $row=[];
                $row['id']=$k;
                $row['name']=$v;
                $card_log_type[]=$row;
            }
            array_unshift($log_pay_type,['id'=>'','name'=>'-----请选择-----']);
        }
        return $log_pay_type;
    }
    /**
     * #User: Administrator
     * #Time: 2023/12/26 14:06
     * #Author:周昌
     * #Description: 增加记录
     * @param $type 0：充值 1开药消费 2：治疗服务消费
     * @param $data array 公共参数：member_id,card_id,money
     * @param null $case_id 病历id 卡消费记录才有
     * @param null $gift_money 赠送金额 卡充值才有
     * @return array
     */
    public static function addCardLog($type,$data,$case_id=null,$gift_money=null)
    {
        $data['hospital_id']=self::getUserHospitalId();
        $data['type']=$type;
        $data['addtime']=time();
        switch ($type){
            case 0:
                $data['explain']='会员卡充值'.$data['money'].'元';
                if($gift_money){
                    $data['gift_money']=$gift_money;
                    $data['explain'].='赠送'.$gift_money.'元';
                }
                break;
            case 1:
                if($case_id){
                    $data['case_id']=$case_id;
                }else{
                    return Tool::Error('缺少case_id参数');
                }
                $data['explain']='开药消费'.$data['money'].'元';
                break;
            case 2:
                if($case_id){
                    $data['case_id']=$case_id;
                }else{
                    return Tool::Error('缺少case_id参数');
                }
                $data['explain']='治疗服务消费'.$data['money'].'元';
                break;
        }
        $res=self::add($data);
        return $res;
    }
    //收入统计
    public static function incomData($where)
    {
        //药品收入
        $medicine_where=[
            'type'=>CardLogService::$card_log_type_index['take_medicine'],
        ];
        $medicine_income=self::$model::where($medicine_where)->where($where)->sum('pay_money');
        //治疗服务收入
        $treatment_where=[
            'type'=>CardLogService::$card_log_type_index['treatment'],
        ];
        $treatment_income=self::$model::where($treatment_where)->where($where)->sum('pay_money');
        $data=[
            ['name'=>'药品收入','money'=>$medicine_income],
            ['name'=>'服务收入','money'=>$treatment_income],
            ['name'=>'总收入','money'=>bcadd($medicine_income,$treatment_income,2)],
        ];
        return json_encode(['rows'=>$data,"total" => count($data)], JSON_UNESCAPED_UNICODE);

    }
    //充值统计
    public static function rechargeData($where)
    {
        $wh=[];
        if(self::getUserHospitalGroupId()){
            $wh=['c.hospital_group_id'=>self::getUserHospitalGroupId()];
        }
        $card_cate=CardCateModel::alias('c')->where($wh)->leftJoin('hospital h','c.hospital_group_id=h.id')
            ->field('c.id,c.name,h.name as hospital_name')->select()->toArray();
        $data=self::$model::where($where)->group('card_cate_id')->column('card_cate_id,sum(money) as total_money','card_cate_id');
//        $data=Db::name('card_cate')->alias('ca')->leftJoin('card c','ca.id=c.card_cate_id')
//            ->leftJoin('card_log l','c.id=l.card_id')->where($where)
//            ->field('ca.name,sum(l.money) as total_money')->group('l.card_cate_id')->select();
        if(!empty($card_cate)){
            foreach ($card_cate as $k=>&$v){
                $v['total_money']=$data[$v['id']]??0;
            }
            $card_cate[]=[
                'id'=>'',
                'name'=>'总计',
                'hospital_name'=>'全部',
                'total_money'=>array_sum(array_column($data,'total_money')),
            ];
        }
        return json_encode(['rows'=>$card_cate,"total" => count($card_cate)], JSON_UNESCAPED_UNICODE);

    }

    //列表数据
    public static function getAjaxData($where)
    {
        $table = self::$model::order('id desc');
        return self::tableJsonData($table, $where, function ($data){
            $data['type_name']=self::$card_log_type[$data['type']];
            $data['total']=bcadd($data['money'],$data['gift_money']);
            $data['pay_type_name']=self::$log_pay_type[$data['pay_type']]??'';
            $data['gift_money']=$data['gift_money']??'';
            $data['pay_money']=$data['pay_money']??'';
            $data['pay_gift']=$data['pay_gift']??'';
            $data['hospital_name'] = $data['hospital_id']?HospitalService::getNameByKey($data['hospital_id'],''):'';
            return $data;
        },function ($data){
            if(!empty($data)){
                //member
                $member_ids=array_column($data,'member_id');
                $member_info_ids=array_column($data,'member_info_id');
                $member=MemberModel::getListColumn([['id','in',$member_ids]],'id,real_name,phone');
                $member_info=MemberInfoModel::getListColumn([['id','in',$member_info_ids]],'id,name');
                foreach ($data as $k=>$v){
                    $data[$k]['family_group']=$member[$v['member_id']]['real_name'].'-'.$member[$v['member_id']]['phone'];
                    $data[$k]['name']=$v['type']==0?$member[$v['member_id']]['real_name']:$member_info[$v['member_info_id']];
                }
            }

            return $data;
        });
    }

}